<template>
  <div>
    <van-form @submit="onSubmit">
      <van-field
        v-model="userInfo.userName"
        name="userName"
        label="用户名"
        placeholder="用户名"
        :rules="[
          { required: true, message: '请填写用户名' },
          {
            validator: value => {
              if (value === '小明') {
                return true
              } else {
                return false
              }
            },
            message: '你不要乱输入，只能输入小明'
          }
        ]"
      />
      <van-field
        v-model="userInfo.pwd"
        type="password"
        name="pwd"
        label="密码"
        placeholder="密码"
        :rules="[
          { required: true, message: '请填写密码' },
          {
            pattern: /^\d{4,8}$/,
            message: '密码是4-8位的数字'
          }
        ]"
      />
      <div style="margin: 16px;">
        <van-button round block type="info" native-type="submit">提交</van-button>
      </div>
    </van-form>
  </div>
</template>

<script>
export default {
  data () {
    return {
      userInfo: {
        userName: '',
        pwd: ''
      }
    }
  },
  methods: {
    onSubmit (params) {
      /*
      模拟接口
      */
      setTimeout(() => {
        const token = 'dwihdj398r93rfiehcdfd'
        const userInfo = {
          nickName: '小花花',
          avatar: 'https://dss1.bdstatic.com/70cFuXSh_Q1YnxGkpoWK1HF6hhy/it/u=899964089,560749134&fm=26&gp=0.jpg'
        }
        /*
        缓存
        */
        localStorage.setItem('token', token)
        localStorage.setItem('userInfo', JSON.stringify(userInfo))
        // 跳转路由
        if (this.$route.query.from) {
          this.$router.replace(this.$route.query.from)
        } else {
          this.$router.replace('/home')
        }
        /*
        取判断是否首次取
        var items = localStorage.getItem('userInfo')
                  ?
                  JOSN.parse(localStorage.getItem('userInfo'))
                  :
                  {}
        */
      }, 2000)
    }
  }
}
</script>

<style lang="scss" scoped>

</style>
